package cn.hongyu.service.impl;

import cn.hongyu.mapper.AccountMapper;
import cn.hongyu.pojo.Account;
import cn.hongyu.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    private AccountMapper accountMapper;

    @Override
    public List<Account> findAll() throws IOException {
        InputStream resource = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resource);
        SqlSession sqlSession = factory.openSession(true);
        accountMapper=sqlSession.getMapper(AccountMapper.class);
        List<Account> list = accountMapper.findAll();
        return list;
    }

    @Override
    public void save(Account account) throws IOException {
        InputStream resource = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resource);
        SqlSession sqlSession = factory.openSession(true);
        accountMapper=sqlSession.getMapper(AccountMapper.class);
        accountMapper.save(account);
        sqlSession.close();
    }
}
